import { Form, Input, Divider, Card, Col, Row, message } from 'antd';
import React, { useState, useEffect } from 'react';
import { HTTP_STATUS } from "@/generic/ConfigParams";

const FormItem = Form.Item;

const requestDecorator = async (requestFunc, modalAction) => {
    const hide = message.loading('正在添加');
    const response = await requestFunc;
    hide();
    console.log('==>> requestDecorator', response)
    // if (response && response.ok) {
    //     message.success('添加成功');
    //     modalAction;  // 使用了Modal时，此处操作 modalVisible
    // }
    // else {
    //     const error_msg = response.status ? HTTP_STATUS[response.status] : "";
    //     message.error(`添加失败！${error_msg}`);
    // }
}

const UpdateForm = props => {

    const { dispatch, currentPage, userInfo, form, detailArgs } = props;
    const { updateTitle, leave, content: contentItems, footer: footerArr, } = detailArgs;
    const [footer, setFooter] = useState('');
    const MARK = 'update';

    const renderContent = () => {

        const formItems = [];

        if (contentItems && currentPage) {
            for (const key in contentItems) {

                contentItems[key].length > 0
                && contentItems[key].forEach((item, i) => {
                    
                    if (item.canUpdate) {
                        const Elem = item.elem || <Input />;
                        // console.log("==>> Elem", Elem)
                        formItems.push(
                            <Col key={`${key}_${i}`} {...detailArgs.defaultColSpan}>
                                <FormItem
                                    labelCol={item.labelCol || detailArgs.defaultLabelCol}
                                    wrapperCol={item.wrapperCol || detailArgs.defaultWrapperCol}
                                    label={item.label}
                                >
                                    {form.getFieldDecorator(item.index, {
                                        ...item.options,
                                        initialValue: userInfo[item.index]
                                    })(Elem)}
                                </FormItem>
                            </Col>
                        )
                    } 
                })
                // formItems.push(<Divider key={formItems.length} />)
            }
        }

        return <Row gutter={[16, 16]}>{formItems}</Row>;
    }

    const onClick = (item) => {
        if (item.isValidate) {
            form.validateFields(async (err, fieldsValue) => {
                if (err) return;
                console.log("==>>validateFields", fieldsValue)
                const updateFields = {};
                for (const key in fieldsValue) {
                    
                    if (form.isFieldTouched(key)) {  // 判断哪些值更改了
                        updateFields[key] = fieldsValue[key];
                    }
                }
                if (!Object.keys(updateFields).length) return;

                // console.log('===>> updateFields:', updateFields)
                requestDecorator(item.onClick(dispatch, userInfo, updateFields));
            });
        }
        else {
            item.onClick(dispatch);
        }

        form.resetFields();
    }

    const renderFooter = () => {
        const footerOpts = [];

        if (footerArr) {
            footerArr.forEach((item, i) => {
                (!item.mark || item.mark == MARK)
                && footerOpts.push(
                    <div key={i} style={{ ...item.style }}>
                        <item.elem {...item.args}
                            onClick={() => onClick(item)}
                        >{item.text}</item.elem>
                    </div>
                )
            })
        }
        return <>{footerOpts}</>;
    }

    useEffect(() => {
        // console.log("==>> contentItems!", contentItems)
        setFooter(renderFooter());
    }, [contentItems])

    useEffect(() => {
        console.log('===>> currentPage', currentPage)
    }, [currentPage])

    return (
        <div style={{ backgroundColor: "#fff" }}>
            <Card
                title={updateTitle}
            // extra={extraRender()}
            >
                {renderContent()}
                <Divider />
                {footer}
            </Card>
        </div>
    );
}

export default Form.create()(UpdateForm);